﻿using System;

namespace Basic
{
    /// <summary>
    /// 异步对象生命周期管理
    /// </summary>
    public abstract class AsyncObject
    {
        /// <summary>
        /// 执行中的异步调用数量
        /// </summary>
        public int AsyncCallCount
        {
            get;
            private set;
        }

        /// <summary>
        /// 是否在使用中
        /// </summary>
        public bool InUsing
        {
            get;
            private set;
        }

        /// <summary>
        /// 是否执行清理：不再异步请求中且不在使用中
        /// </summary>
        protected bool IsOver
        {
            get
            {
                return AsyncCallCount == 0 && !InUsing;
            }
        }

        /// <summary>
        /// 能否执行一次异步调用
        /// </summary>
        /// <returns>是否能执行异步调用</returns>
        protected bool StartAsyncCall()
        {
            if (InUsing)
            {
                AsyncCallCount++;
                return true;
            }
            return false;
        }

        /// <summary>
        /// 一次异步调用结束
        /// </summary>
        protected void OnAsyncCallOver()
        {
            AsyncCallCount--;

            if (IsOver)
            {
                DoSafeClear();
            }
        }

        /// <summary>
        /// 更新是否在使用中
        /// </summary>
        /// <param name="inUsing"></param>
        protected void SetInUsing(bool inUsing)
        {
            InUsing = inUsing;

            if (IsOver)
            {
                DoSafeClear();
            }
        }

        /// <summary>
        /// 不再异步请求中且不在使用中时，执行清理
        /// </summary>
        protected abstract void DoSafeClear();
    }
}
